import { InjectRedis } from '@liaoliaots/nestjs-redis';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { Redis } from 'ioredis';
import { random, sleep } from 'radash';

@Injectable()
export class UtilService {
  constructor(
    @InjectRedis()
    private readonly redis: Redis,
    private readonly config: ConfigService,
  ) {}

  async sleep(ms: number) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  async wait(id: number, ip: string) {
    const ms = random(1, 10) * 100;
    console.log(`随机睡眠: ${ms}ms - user: ${id} - ip: ${ip}`);
    await sleep(ms);
  }

  async getBase64Image(url: string) {
    if (!url) return url;
    try {
      const res = await axios.get(
        url + '?x-oss-process=image/resize,w_800/quality,Q_80',
        {
          responseType: 'arraybuffer',
        },
      );
      if (!!res.data) {
        return (
          'data:image/png;base64,' + Buffer.from(res.data).toString('base64')
        );
      }
      return url;
    } catch (e) {
      return null;
    }
  }

  async cleanKeys(key: string) {
    const keyPrefix = this.config.get('redis.keyPrefix') + ':';
    const redisKey = keyPrefix + key;

    let keys = await this.redis.keys(redisKey);

    if (!!keys && keys.length > 0) {
      keys = keys.map((k) => k.substring(keyPrefix.length, k.length));
      await this.redis.del(...keys);
    }
  }

  async cleanList(key: string) {
    await this.redis.del(key);
  }
}
